package com.lsy.wallet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsy.wallet.mapper.DealRunningWaterMapper;
import com.lsy.wallet.mapper.UserWalletMapper;
import com.lsy.wallet.pojo.DealRunningWater;
import com.lsy.wallet.pojo.UserWallet;
import com.lsy.wallet.service.api.DealRunningWaterService;
import com.lsy.wallet.service.api.UserWalletService;
import com.lsy.wallet.vo.ConsumptionVo;
import com.lsy.wallet.vo.RefundVo;
import javafx.scene.input.DataFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author lsyandwh
 * @create 2023-03-07 16:55
 */
@Service
public class DealRunningWaterServiceImpl implements DealRunningWaterService {

    @Autowired
    private DealRunningWaterMapper dealRunningWaterMapper;

    @Autowired
    private UserWalletService userWalletService;

    @Autowired
    private UserWalletMapper userWalletMapper;

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    @Override
    public String consumption(ConsumptionVo consumptionVo) {

        //1.校验密码
        Long rollOutWalletId = consumptionVo.getRollOutWalletId();//转出用户钱包id
        UserWallet userWallet = userWalletMapper.selectById(rollOutWalletId);
        if(null == userWallet) throw new RuntimeException("请求非法");

        if(! consumptionVo.getPayPassword().equals(userWallet.getPayPassword())) throw new RuntimeException("密码错误");

        //2.检查交易用户余额是否充足
        BigDecimal balance = userWallet.getAvailableBalance();//可用余额
        BigDecimal money = consumptionVo.getMoney();//交易金额
        if (balance.compareTo(money) == -1) throw new RuntimeException("余额不足，请充值");

        //3.用户加减余额
        userWalletService.addAndSubtractBalance(consumptionVo);

        //4.生成订单流水号
        String runningWaterId = generateRunningWaterId(consumptionVo.getRollOutWalletId());

        //组装数据
        DealRunningWater dealRunningWater = new DealRunningWater();
        BeanUtils.copyProperties(consumptionVo,dealRunningWater);
        dealRunningWater.setRunningWaterId(runningWaterId);
        dealRunningWater.setDealStatus("交易中");//TODO 实际开发中应该用枚举
        dealRunningWater.setDealType("购物");
        dealRunningWater.setCreateTime(new Date());
        dealRunningWater.setUpdateTime(new Date());
        dealRunningWater.setIsDeleted(0);

        //插入数据
        dealRunningWaterMapper.insert(dealRunningWater);

        return runningWaterId;
    }

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    @Override
    public void refund(RefundVo refundVo) {

        //1.判断交易是否完成或已退款
        QueryWrapper<DealRunningWater> wrapper = new QueryWrapper<>();
        wrapper.eq("running_water_id",refundVo.getRunningWaterId())
                .eq("order_id",refundVo.getOrderId());
        DealRunningWater dealRunningWater = dealRunningWaterMapper.selectOne(wrapper);

        String dealStatus = dealRunningWater.getDealStatus();
        if("交易完成".equals(dealStatus) || "交易退款".equals(dealStatus)) throw new RuntimeException("交易已完成");


        //2.判断交易金额是否正确
        BigDecimal refundMoney = refundVo.getRefundMoney();
        BigDecimal money = dealRunningWater.getMoney();
        if(money.compareTo(refundMoney) == -1) throw new RuntimeException("退款金额大于交易金额");

        //3.执行退款
        //更新原订单交易状态
        dealRunningWater.setDealStatus("交易退款");
        dealRunningWaterMapper.updateById(dealRunningWater);

        //生成退款交易流水
        DealRunningWater refundDealRunningWater = new DealRunningWater();
        String runningWaterId = generateRunningWaterId(dealRunningWater.getRollOutWalletId());
        refundDealRunningWater.setRunningWaterId(runningWaterId);
        refundDealRunningWater.setOrderId(refundVo.getOrderId());
        refundDealRunningWater.setRollOutWalletId(0L);//TODO 退款统一设定转出钱包为 0
        refundDealRunningWater.setShiftToWalletId(dealRunningWater.getRollOutWalletId());
        refundDealRunningWater.setMoney(refundMoney);
        refundDealRunningWater.setDealStatus("交易完成");
        refundDealRunningWater.setDealType("退款");
        refundDealRunningWater.setCreateTime(new Date());
        refundDealRunningWater.setUpdateTime(new Date());
        refundDealRunningWater.setIsDeleted(0);
        dealRunningWaterMapper.insert(refundDealRunningWater);

        //更新用户钱包
        userWalletService.refund(dealRunningWater.getRollOutWalletId(),refundMoney);
    }

    @Override
    public List<DealRunningWater> getDealRunningWaterList(Long userId) {

        //查询用户钱包信息
        UserWallet userWallet = userWalletService.getWalletDetailByUserId(userId);

        QueryWrapper<DealRunningWater> wrapper = new QueryWrapper<>();
        wrapper.eq("roll_out_wallet_id",userWallet.getId())
                .or()
                .eq("shift_to_wallet_id",userWallet.getId());

        List<DealRunningWater> list = dealRunningWaterMapper.selectList(wrapper);

        return list;
    }

    /**
     * 生成交易流水
     * @param rollOutWalletId
     * @return
     */
    private String generateRunningWaterId(Long rollOutWalletId){
        String runningWaterId = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        runningWaterId = runningWaterId + rollOutWalletId;
        return runningWaterId;
    }


}
